<template>
  <div class="revenue-wrapper">
    <div class="title-wrappe mt24">
      <div class="flex-center-between mh24">
        <div class="flex-center">
          <div class="bag-6a66f6-radius-2px" style="width: 4px; height: 16px; margin-right: 12px"></div>
          <span class="font-16px-3x3d43 mr24">营收金额趋势</span>
        </div>
        <a-range-picker
          :allowClear="false"
          class="datePicker"
          :placeholder="['开始月份', '结束月份']"
          format="YYYY-MM"
          style="width: 280px"
          :mode="mode"
          v-model="value"
          @panelChange="handlePanelChange2"
        ></a-range-picker>
      </div>
    </div>
    <div id="revenueChart" class="chart-basic"></div>
  </div>
</template>

<script>
import moment from "moment";
import echarts from "echarts";
import { selectRevenueAmountCount } from "../api";
export default {
  props: ["siteId"],
  data() {
    return {
      colors: localStorage.getItem("primary"),
      mode: ["month", "month"],
      value: [`${moment().subtract(5, "months").format("YYYY-MM")}`, `${moment().format("YYYY-MM")}`],
      queryType: 1,
      chartMonths: [],
      chartData: []
    };
  },
  watch: {
    value(val) {
      this.selectRevenueAmountCount(val);
      this.chartMonths = this.getDiffDate(this.value[0], this.value[1]);
    },
    siteId(newValue) {
      this.selectRevenueAmountCount(this.value);
      // console.log("debug log --> newValue", newValue);
    }
  },
  computed: {},
  mounted() {
    this.selectRevenueAmountCount(this.value);
    this.chartMonths = this.getDiffDate(this.value[0], this.value[1]);
  },
  methods: {
    handlePanelChange2(value, mode) {
      this.value = value;
    },
    showChart() {
      this.$nextTick(() => {
        var myChart = echarts.init(document.getElementById("revenueChart"));
        var option = {
          tooltip: {
            trigger: "axis",
            axisPointer: {
              type: "cross",
              label: {
                backgroundColor: "#6a7985"
              }
            }
          },
          grid: {
            left: "3%",
            right: "4%",
            bottom: "3%",
            top: "32px",
            containLabel: true
          },
          xAxis: [
            {
              type: "category",
              boundaryGap: false,
              data: this.chartMonths,
              axisLine: {
                lineStyle: {
                  color: "#767885"
                }
              }
            }
          ],
          yAxis: [
            {
              type: "value",
              axisLine: {
                lineStyle: {
                  color: "#767885"
                }
              }
            }
          ],
          series: [
            {
              name: "营收总金额",
              type: "line",
              stack: "总量",
              smooth: true,
              areaStyle: {
                normal: {
                  color: this.colors // 改变区域颜色
                }
              },
              itemStyle: {
                normal: {
                  color: this.colors, // 改变折线点的颜色
                  lineStyle: {
                    color: this.colors // 改变折线颜色
                  }
                }
              },
              emphasis: {
                focus: "series"
              },
              data: this.chartData
            }
          ]
        };
        myChart.setOption(option);
        window.onresize = myChart.resize;
      });
    },
    selectRevenueAmountCount(data) {
      const da = {
        startDate: moment(data[0]).startOf("month").format("YYYY-MM-DD"),
        endDate: moment(data[1]).endOf("month").format("YYYY-MM-DD")
      };
      if (this.siteId && this.siteId !== "undefined" && this.siteId !== "-1") {
        da.companyIds = this.siteId;
      }
      selectRevenueAmountCount(da)
        .then((res) => {
          const data = res.data;
          this.chartData = new Array(this.chartMonths.length).fill(0);
          data.forEach((element) => {
            const yearly = element.yearly;
            const monthlyString = element.monthly + "";
            const monthly = monthlyString.length === 1 ? "0" + element.monthly : element.monthly.toString;
            const chartMonthsPos = this.chartMonths.indexOf(yearly + "-" + monthly);
            this.chartData.splice(chartMonthsPos, 1, element.totalAmount);
          });
          this.showChart();
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    getDiffDate(minDate, maxDate) {
      const months = [];
      const startDate = new Date(moment(minDate).format("YYYY-MM-DD"));
      const endDate = new Date(moment(maxDate).format("YYYY-MM-DD"));
      // 把时间的天数都设置成当前月第一天
      startDate.setDate(1);
      endDate.setDate(1);
      // new Date(yyyy-MM-dd) 不知为何有时候小时是 08 有时候是00
      endDate.setHours(0);
      startDate.setHours(0);
      while (endDate.getTime() >= startDate.getTime()) {
        const year = startDate.getFullYear();
        let month = startDate.getMonth() + 1;
        // 加一个月
        startDate.setMonth(month);
        if (month.toString().length === 1) {
          month = "0" + month;
        }
        months.push(year + "-" + month);
      }
      return months;
    }
  }
};
</script>

<style lang="scss" scoped>
.revenue-wrapper {
  display: flex;
  flex-direction: column;
  padding-bottom: 24px;
  .title-wrapper {
    display: flex;
    align-items: center;
    .datePicker {
      width: 254px;
    }
  }

  .bag-6a66f6-radius-2px {
    background: var(--primary);
    border-radius: 2px;
  }

  .chart-basic {
    height: 340px;
    width: 100%;
    overflow-y: hidden;
    white-space: nowrap;
  }

  .font-16px-3x3d43 {
    font-size: 16px;
    font-weight: 500;
    color: #3c3d43;
    line-height: 24px;
  }
}
</style>
